# This is a sample Python script.
import cv2
import os

from PIL import Image,ImageDraw
import face_recognition

from mask import create_mask
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.

def main():

    #基本的hear+adaboost算法实现人脸检测
    img=cv2.imread('1.jpg')
    gray=cv2.cvtColor(img,cv2.COLOR_BGR2BGRA)
    face_cascade=cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')
    face_cascade.load('haarcascade_frontalface_alt2.xml')
    faces=face_cascade.detectMultiScale(gray,1.3,5)  #1.3为缩放比例；5表示每个对象至少被检测的次数

    for (x,y,w,h) in faces:
        img=cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) #(255,0,0)表示线的颜色；2表示线框
        cv2.imshow('img',img)
        cv2.waitKey()


def main():

    #提取图片上人脸的特征点并在图上绘图
    image = face_recognition.load_image_file('two_people.jpg')  #读取照片
    face_landmarks_list = face_recognition.face_landmarks(image)  #对照片关键点进行提取
    print('I found {} face(s) in this photograph'.format(len(face_landmarks_list)))  #输出找到几张人脸

    pil_image = Image.fromarray(image)  #将图片变为能写入的状态
    d = ImageDraw.Draw(pil_image)  #创建可以进行绘图的图片

    for face_landmarks in face_landmarks_list:  #每张脸

        for facial_feature in face_landmarks.keys():  #每个部位
            print('The {} in this face has the following points: {}'.format(facial_feature,
                                                                            face_landmarks[facial_feature]))

            for facial_feature in face_landmarks.keys():
                d.line(face_landmarks[facial_feature], width=5)  #引用绘图对象进行画图，5为线框
    pil_image.show()


def main():

    #根据关键点定位进行人脸上装操作
    image = face_recognition.load_image_file("obama.jpg")  #加载图片

    # Find all facial features in all the faces in the image
    face_landmarks_list = face_recognition.face_landmarks(image)  #获取特征点

    pil_image = Image.fromarray(image)   #将图片变为能写入的状态
    for face_landmarks in face_landmarks_list:
        d = ImageDraw.Draw(pil_image, 'RGBA')  #创建绘图对象，变为可编辑的

        # 画个浓眉
        d.polygon(face_landmarks['left_eyebrow'], fill=(68, 54, 39, 128))  #左眼
        d.polygon(face_landmarks['right_eyebrow'], fill=(68, 54, 39, 128))  #右眼
        d.line(face_landmarks['left_eyebrow'], fill=(1, 1, 1, 1), width=15)  #左眼画线
        # d.line(face_landmarks['left_eyebrow'], fill=(68, 54, 39, 150), width=5)
        d.line(face_landmarks['right_eyebrow'], fill=(68, 54, 39, 150), width=5)  #右眼画线

        # 涂个性感的嘴唇
        d.polygon(face_landmarks['top_lip'], fill=(150, 0, 0, 128))  #上嘴唇
        d.polygon(face_landmarks['bottom_lip'], fill=(150, 0, 0, 128)) #下嘴唇
        d.line(face_landmarks['top_lip'], fill=(150, 0, 0, 128), width=8)
        d.line(face_landmarks['bottom_lip'], fill=(150, 0, 0, 128), width=1)

        # 闪亮的大眼睛
        d.polygon(face_landmarks['left_eye'], fill=(255, 255, 255, 30))
        d.polygon(face_landmarks['right_eye'], fill=(255, 255, 255, 30))

        # 画眼线
        # d.line(face_landmarks['left_eye'] + [face_landmarks['left_eye'][0]], fill=(0, 0, 0, 110), width=6)
        # d.line(face_landmarks['right_eye'] + [face_landmarks['right_eye'][0]], fill=(0, 0, 0, 110), width=6)
        d.line(face_landmarks['left_eye'] + [face_landmarks['left_eye'][0]], fill=(0, 0, 0, 110), width=6)
        d.line(face_landmarks['right_eye'] + [face_landmarks['right_eye'][0]], fill=(0, 0, 0, 110), width=6)
        pil_image.show()



def main():

    #视频中进行宽的选取，并进行人脸相似度进行匹配
    input_movie = cv2.VideoCapture("Huanlesong1.mp4")   #读取视频
    length = int(input_movie.get(cv2.CAP_PROP_FRAME_COUNT))  #对视频进行长度的判别，进行逐帧的处理

    # Create an output movie file (make sure resolution/frame rate matches input video!)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')  #指定编解码器
    # fourcc 本身是一个 32 位的无符号数值，用 4 个字母表示采用的编码器。
    #  常用的有 “DIVX"、”MJPG"、“XVID”、“X264"。可用的列表在这里。

    # 推荐使用 ”XVID"，但一般依据你的电脑环境安装了哪些编码器。
    output_movie = cv2.VideoWriter('output.avi', fourcc, 25, (640, 360)) #帧数跟视频的长宽（根据视频进行制定）

    lmm_image = face_recognition.load_image_file("Qidian.png")
    lmm_face_encoding = face_recognition.face_encodings(lmm_image)[0]

    al_image = face_recognition.load_image_file("Quxiaoxiao.png")
    al_face_encoding = face_recognition.face_encodings(al_image)[0] #编码

    known_faces = [
        lmm_face_encoding,
        al_face_encoding
    ]

    # Initialize some variables
    face_locations = []  #框的位置
    face_encodings = []  #编码的地址
    face_names = []      #人的名字
    frame_number = 0

    while True:
        # Grab a single frame of video
        ret, frame = input_movie.read()
        frame_number += 1

        # Quit when the input video file ends
        if not ret:  #是否为最后一张图片
            break
        rgb_frame = frame[:, :, ::-1]   #BGR color to RGB color

        # Find all the faces and face encodings in the current frame of video
        face_locations = face_recognition.face_locations(rgb_frame)  #框的定位
        face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)  #编码

        face_names = []
        for face_encoding in face_encodings:
            # See if the face is a match for the known face(s)
            match = face_recognition.compare_faces(known_faces, face_encoding, tolerance=0.50)  #进行判别
            # If you had more than 2 faces, you could make this logic a lot prettier
            # but I kept it simple for the demo
            name = None
            if match[0]:  #
                name = "Qidian"
            elif match[1]:
                name = "Quxiaoxiao"

            face_names.append(name)

        # Label the results
        for (top, right, bottom, left), name in zip(face_locations, face_names):
            if not name:
                continue

            # Draw a box around the face
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)  #画原始框

            # Draw a label with a name below the face
            cv2.rectangle(frame, (left, bottom - 25), (right, bottom), (0, 0, 255), cv2.FILLED)  #文字的框
            font = cv2.FONT_HERSHEY_DUPLEX
            cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.5, (255, 255, 255), 1)  #写文字

        # Write the resulting image to the output video file
        print("Writing frame {} / {}".format(frame_number, length))  #记录视频播放的位置
        output_movie.write(frame)

    # All done!
    input_movie.release()
    cv2.destroyAllWindows()


#口罩的添加，脚本
folder_path =r"C:\Users\kiwi\Desktop\face-mask-detector\Data_Generator\Downloads"

images = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
for i in range(len(images)):
    print("the path of the image is", images[i])
    #image = cv2.imread(images[i])
    #c = c + 1
    create_mask(images[i])



if __name__ == '__main__':
    print_hi('PyCharm')

